﻿using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using Common.Logging;
using Newtonsoft.Json;
using Qy.Yzrb.Helpers;

namespace Qy.Yzrb.Pipeline.ActionFilters
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class TokenRequiredAttribute : AuthorizationFilterAttribute
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(TokenRequiredAttribute));

        public override void OnAuthorization(HttpActionContext actionContext)
        {
            if (actionContext == null)
                throw new ArgumentNullException(nameof(actionContext));

            var canSkip = SkipAuthorization(actionContext);

            var userId = "";

            var isAuth = GetUserInfo(actionContext.Request, out userId);

            if (isAuth)
            {
                AzUser.SetInApi(actionContext.Request, userId);
            }

            if (!isAuth && !canSkip)
            {
                HandleUnauthorizedRequest(actionContext);
            }
        }

        private bool SkipAuthorization(HttpActionContext actionContext)
        {
            return actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any<AllowAnonymousAttribute>() ||
                actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any<AllowAnonymousAttribute>();
        }

        private void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            actionContext.Response = actionContext.ControllerContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
        }

        private bool GetUserInfo(HttpRequestMessage request, out string userId)
        {
            userId = "";

            try
            {
                CookieHeaderValue cookie = request.Headers.GetCookies("AzuCookie").FirstOrDefault();

                if (cookie != null)
                {
                    //此处系统会自动UrlDecode
                    var token = cookie["AzuCookie"].Value;

                    var isVerified = JwtTokenHelper.ValidateJwtToken(token, out userId);

                    if (isVerified)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                Logger.Error(JsonConvert.SerializeObject(ex));
                return false;
            }
        }
    }
}